package com.doradance.wxapi;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Switch;
import android.widget.Toast;

import com.doradance.account.Account;
import com.doradance.account.AccountManager;
import com.doradance.account.UrlCenter;
import com.doradance.account.ui.LoginActivity;
import com.doradance.account.ui.LoginPhoneActivity;
import com.doradance.account.utils.ShareUtil;
import com.doradance.account.utils.WechatHelper;
import com.doradance.app.MainActivity;
import com.doradance.app.appactivity.AddBabyActivity;
import com.doradance.app.appactivity.SelectBabyActivity;
import com.doradance.app.home.CoursesDetailActivity;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.common.http.TokenInfo;
import com.doradance.entity.CoursesIdEntity;
import com.doradance.entity.ShareBackEntity;
import com.doradance.entity.WexinBean;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.GsonUtils;
import com.pachong.android.frameworkbase.utils.io.SharePreferenceUtil;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.umeng.socialize.weixin.view.WXCallbackActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static com.doradance.account.AccountManager.getTokenInfo;
import static com.doradance.account.UrlCenter.WX_LOGIN;
import static com.doradance.account.ui.LoginPhoneActivity.LOGINADD;


/**
 * 微信的分享回调页面
 *
 * 只要AndroidManifest等配置正确，友盟就可以正确回调微信的分享结果，不需要我们再处理
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016-07-11
 * @Version: 1.0.0
 */

public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {
    private static String TAG = "WXEntryActivity";
    String optimize;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IWXAPI iwxapi = WechatHelper.getInstance().init(this);
        iwxapi.handleIntent(getIntent(), this);
    }


    @Override
    public void onReq(BaseReq baseReq) {
        Log.e(TAG, "onReq");
    }

    @Override
    public void onResp(BaseResp baseResp) {
        Log.e(TAG, "onResp"+baseResp.errCode);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (baseResp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH:
                        String code = ((SendAuth.Resp) baseResp).code;
                        if (TextUtils.isEmpty(code)) {
                            EasyToast.showToast(WXEntryActivity.this, "抱歉~微信授权失败", Toast.LENGTH_SHORT);
                            return;
                        }
                        getOpenID(code);
                        break;
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        finish();
                        EasyToast.showToast(WXEntryActivity.this, "分享成功", Toast.LENGTH_SHORT);
                        if(ShareUtil.getShareChapterId()!=-1){
//                            EventBus.getDefault().post(new ShareBackEntity());
//                            initShareCharpter();
                            CoursesDetailActivity a = new CoursesDetailActivity();
                            a.CoursesDetailActivity.finish();
                            CoursesDetailActivity.start(WXEntryActivity.this,ShareUtil.getShareCourseId());
                        }
                    break;

                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                switch (baseResp.getType()) {
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                    EasyToast.showToast(WXEntryActivity.this, "分享取消", Toast.LENGTH_SHORT);
                    if(ShareUtil.getShareChapterId()!=-1){
                        ShareUtil.setShareChapterId(-1);
                        CoursesDetailActivity a = new CoursesDetailActivity();
                        a.CoursesDetailActivity.finish();
                        CoursesDetailActivity.start(WXEntryActivity.this,ShareUtil.getShareCourseId());
                    }
                    finish();
                    break;
                }
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://分享拒绝
                Toast.makeText(WXEntryActivity.this, "分享失败", Toast.LENGTH_LONG).show();
                if(ShareUtil.getShareChapterId()!=-1){
                    ShareUtil.setShareChapterId(-1);
                    CoursesDetailActivity a = new CoursesDetailActivity();
                    a.CoursesDetailActivity.finish();
                    CoursesDetailActivity.start(WXEntryActivity.this,ShareUtil.getShareCourseId());
                }
                finish();
                break;
        }

    }



    //通过code获取openid
    private void getOpenID(String code) {
        IHttpRequest request = new HttpRequest(getBaseContext());
        UrlParams params = new UrlParams();
        params.put("code",code);
        request.get(WX_LOGIN, params, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                try {
                    JSONObject jsonObject = new JSONObject(o);
                    optimize = jsonObject.getString("optimize");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("optimize1",optimize);
                WexinBean wexinBean = GsonUtils.string2Object(o, WexinBean.class);
                WexinBean.TokenBean token = wexinBean.getToken();
                TokenInfo tokenInfo = getTokenInfo();
                tokenInfo.setAccessToken(token.getAccess_token());
                tokenInfo.setExpiresAt(token.getExpires_at());
                tokenInfo.setMacKey(token.getMac_key());
                tokenInfo.setRefreshToken(token.getRefresh_token());
                tokenInfo.setServerTime(token.getServer_time());
                if(tokenInfo!=null && optimize.equals("false")){
                    AddBabyActivity.start(WXEntryActivity.this,LOGINADD);
                    finish();
                    SharePreferenceUtil.saveString(getApplicationContext(),"isOptimize","isOptimize","false");
                }else{
                    SelectBabyActivity.start(WXEntryActivity.this);
                    finish();
                }
            }

            @Override
            public void enableProgress(boolean enableProgress) {
                super.enableProgress(enableProgress);
                if(enableProgress){
                    enableProgress(false);
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
//
    }

//    //服务端通过openid 判断是否绑定了
//    private void ifBindPhone(final String openId,final String token) {
//        IHttpRequest request = new HttpRequest(getBaseContext());
//        UrlParams params = new UrlParams();
//        params.put("open_id",openId);
//        request.get(UrlCenter.WX_LOGIN, params, new DataRequestListener<TokenInfo>(TokenInfo.class) {
//            @Override
//            public void onStart(Context context, String url) {
//                super.onStart(context, url);
//            }
//            @Override
//            public void onSuccess(TokenInfo o) {
//                super.onSuccess(o);
//                Log.e("ooooo", "25525");
//                //尝试对空字符串进行操作，并捕获异常，输出异常
//                if (TextUtils.isEmpty(o.getAccessToken())) {
//                    //未绑定手机号 要获得微信的信息
//                    Log.e("ooooo", "未绑定");
////                    getUserMesg(openId, token);
//                } else {
//                    Log.e("ooooo", o.toString());
//                    AccountManager.updateTokenInfo(o);
//                    setAccount(o);
//                }
//            }
//            @Override
//            public void onFailure(Throwable t, int errorNo, String strMsg) {
//                super.onFailure(t, errorNo, strMsg);
//            }
//        });
//    }
    /**
     * 获取微信的个人信息
     *
//     */
//    private void getUserMesg(final String openid,final String access_token) {
//        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
//                + access_token
//                + "&openid="
//                + openid;
//        Log.e("ooooooo",path);
//        IHttpRequest request = new HttpRequest(getBaseContext());
//        request.get(path, null, new DataRequestListener<String>(String.class) {
//            @Override
//            public void onStart(Context context, String url) {
//                super.onStart(context, url);
//            }
//            @Override
//            public void onSuccess(String o) {
//                super.onSuccess(o);
//                Log.e("ooooooo",o);
//                WxBindActivity.start(WXEntryActivity.this,o);
//                finish();
//            }
//
//            @Override
//            public void onFailure(Throwable t, int errorNo, String strMsg) {
//                super.onFailure(t, errorNo, strMsg);
//            }
//        });
//
//    }

    private void setAccount(final TokenInfo o) {
        IHttpRequest request = new MyHttpRequest(getBaseContext());
        String requestUrl = String.format(UrlCenter.USER);
        request.get(requestUrl, null, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onSuccess(Account account) {
                AccountManager.setCurrentAccount(account);
                EasyToast.showToast(getBaseContext(), "登录成功");
                AddBabyActivity.start(WXEntryActivity.this);
                finish();
            }
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                EasyToast.showToast(WXEntryActivity.this, strMsg);
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//           finish();
        }
        return false;
    }

}
